<template>
  <el-aside :width="isCollapse ? '64px' : '200px'">
    <el-scrollbar wrap-class="scrollbar-wrapper">
      <template v-if="!permissionStore.hasGenerated">
        <div class="loading-container">
          <span class="loading-text">路由加载中...</span>
        </div>
      </template>
      <el-menu
        v-else
        :default-active="activeMenu"
        unique-opened
      >
        <template v-for="route in processedRoutes" :key="route.path">
          <!-- 修改子菜单判断条件 -->
          <el-sub-menu 
            v-if="route.children?.length"
            :index="route.path"
          >
            <template #title>
              <span>{{ route.meta?.title || route.name }}</span>
            </template>
            <!-- 嵌套渲染子路由 -->
            <el-menu-item
              v-for="child in route.children"
              :key="child.path"
              :index="resolvePath(route.path, child.path)"
              @click="handleMenuItemClick(child)"
            >
              {{ child.meta?.title || child.name }}
            </el-menu-item>
          </el-sub-menu>

          <!-- 单一路由项 -->
          <el-menu-item
            v-else
            :index="route.path"
            @click="handleMenuItemClick"
          >
          
            <span>{{ route.meta?.title || route.name }}</span>
          </el-menu-item>
        </template>
      </el-menu>
    </el-scrollbar>
  </el-aside>
</template>

<script setup>
import { computed,onMounted } from 'vue'
import { useRoute ,useRouter} from 'vue-router'
import { usePermissionStore } from '@/stores/permission'

const route = useRoute()
const router = useRouter()
const permissionStore = usePermissionStore()

// 路径格式化方法
const cleanPath = (path) => {
  return path?.replace(/^\/+/, '') || ''
}

// 处理后的路由数据
// 添加路由加载日志
onMounted(() => {
  console.log(permissionStore)
  console.log('侧边栏初始化完成，当前权限路由:', permissionStore.routes)
  console.log('处理后的路由数据:', processedRoutes.value)
})

const processedRoutes = computed(() => {
  const dashboardRoute = permissionStore.routes.find(r => r.path === 'dashboard')
  console.log('当前dashboard路由:', dashboardRoute) // 新增日志
  return dashboardRoute?.children || []
})

const activeMenu = computed(() => {
  const active = route.meta.activeMenu || cleanPath(route.path)
  console.log('当前激活菜单:', active) // 新增日志
  return active
})

// 页面跳转时添加日志
const handleMenuItemClick = (route) => {
  console.log('菜单点击事件:', {
    routeName: route.name,
    routePath: route.path,
    fullPath: router.resolve(route).href
  })
  router.push({
    name: route.name
  })
}
</script>

<style lang="scss" scoped>
.el-aside {
  transition: width 0.3s ease;
  background-color: #001529;

  .el-menu {
    border-right: none;
    &:not(.el-menu--collapse) {
      width: 200px;
    }
  }
}

.loading-container {
  padding: 20px;
  text-align: center;

  .loading-text {
    color: #fff;
    font-size: 14px;
  }
}
</style>